package com.tlw.practice.tlw.service.impl;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tlw.practice.tlw.common.CommonResult;
import com.tlw.practice.tlw.common.ResultCode;
import com.tlw.practice.tlw.dao.UserDao;
import com.tlw.practice.tlw.entity.UserEntity;
import com.tlw.practice.tlw.exception.BusinessException;
import com.tlw.practice.tlw.pojo.dto.UserDto;
import com.tlw.practice.tlw.pojo.form.UserLoginForm;
import com.tlw.practice.tlw.service.UserService;
import com.tlw.practice.tlw.utils.JWTUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.SignatureException;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public String login(String username, String password) {
        UserEntity user = userDao.findUserEntityByUsernameAndPassword(username, password);
        if (user != null){
            return JWTUtils.generateToken(new UserLoginForm(username, password));
        }
        // 抛出登陆异常
        throw new BusinessException(CommonResult.error(ResultCode.USER_NOT_FOUND));
    }

    @Override
    public UserDto getUserInfoByUsername(String username) {
        UserDto userDto = new UserDto();
        UserEntity userEntity = userDao.findOneByUsername(username);
        BeanUtils.copyProperties(userEntity, userDto);
        System.out.println(userDto);
        return userDto;
    }

    @Override
    public String getUsernameById(String userId) {
        UserEntity user = userDao.findUserEntityById(userId);
        return Optional.ofNullable(user.getUsername()).orElse(null);
    }
}
